package com.example.book.service;

import com.example.book.enums.BookStatusEnum;
import com.example.book.mapper.BookInfoMapper;
import com.example.book.model.BookInfo;
import com.example.book.model.PageRequest;
import com.example.book.model.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
@Slf4j
public class BookService {
    @Autowired
    BookInfoMapper bookInfoMapper;
    public PageResult<BookInfo> getBookList(PageRequest pageRequest) {
        if(pageRequest.getPageSize() < 0 || pageRequest.getCurrentPage() < 1) {
            return null;
        }
        // 从数据库拿取需要的值
        List<BookInfo> bookInfos = null;
        try {
            bookInfos = bookInfoMapper.selectBookInfoByPage(pageRequest);
        }catch (Exception e) {
            log.info("查询翻页信息有误,e:{}",e);
        }
        // 处理是否可借阅信息
        for(BookInfo bookInfo : bookInfos) {
            bookInfo.setStatusCN(BookStatusEnum.getNameByCode(bookInfo.getStatus()).getNaem());
        }

        return new PageResult<>(bookInfos, bookInfoMapper.selectCount(),pageRequest);
    }
    public BookInfo queryBookInfoById(Integer id) {
        return bookInfoMapper.queryBookInfoById(id);
    }

    public Integer updateBook(BookInfo bookInfo) {
        Integer result = null;
        try {
            result = bookInfoMapper.updateBook(bookInfo);
        }catch (Exception e) {
            log.error("更新图书失败: {}",e);
        }
        return result;
    }

    public Integer addBook(BookInfo bookInfo) {
        Integer integer = 0;
        try{
            integer = bookInfoMapper.isnertBook(bookInfo);
        }catch (Exception e) {
            log.info("添加图书失败: {}",e);
        }
        return integer;
    }

    public Integer batchDelete(List<Integer> ids) {
        Integer integer = 0;
        try {
            integer = bookInfoMapper.batchDelete(ids);
        }catch (Exception e) {
            log.error("删除图书失败:{}",e);
        }
        return integer;
    }
}
